import java.awt.font.NumericShaper;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-06-15
 * Time: 21:14
 */

public class Solution {
    public int[] arr;
    public int findPeakElement(int[] nums) {
        this.arr = nums;
        int len = nums.length;
        int left = 0;
        int right = len - 1;
        while (left <= right) {
            int mid = ((right - left) >> 1) + left;
            // 判断如果是峰顶直接返回
            if (compare(mid-1, mid) < 0 && compare(mid, mid+1) > 0) {
                return mid;
            }else if (compare(mid, mid+1) < 0) {
                // 只要右边大, 那么就往右走, 右边一顶有峰顶, 并且左边的一定不用再遍历了
                left = mid + 1;
            }else{
                // 否则往左走, 同理, 只要往左走, 左边一定也有峰顶, 并且右边的已经不用再遍历了
                right = mid - 1;
            }
        }
        return -1;
    }

    private int compare(int index1, int index2) {
        // 主要处理 下标越界的情况
        if (index1 == -1) {
            return 1;
        }
        if (index2 == arr.length) {
            return -1;
        }
        return arr[index1] < arr[index2] ? 1 : -1;
    }
}
